import json
import time
import traceback
import selenium
from selenium import webdriver
from utils.yaml_file_utils import read_common

import sys

import pyperclip
from selenium.webdriver import Keys, ActionChains
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import wait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.relative_locator import locate_with
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support.ui import Select

from publisher.common_handler import wait_login
from utils.file_utils import read_file_with_footer, parse_front_matter, download_image
from utils.yaml_file_utils import read_jianshu, read_common, read_segmentfault, read_oschina, read_zhihu, read_51cto, \
    read_infoq, read_txcloud, read_csdn
import time

## start_page ###############################################################################
def init_driver():
    common_config = read_common()
    driver_type = common_config['driver_type']
    chrome_path = common_config['chrome_path']

    print(f"driver_type={json.dumps(common_config, indent=4)}")

    if driver_type != 'chrome':
        print(f"请使用chrome浏览器")
        exit(0)

    # 启动浏览器驱动服务，设置Chrome 的调试地址
    print(f"=====启动浏览器驱动服务，设置Chrome 的调试地址=====")
    print(f"service_location={common_config['service_location']}")
    print(f"debugger_address={common_config['debugger_address']}")
    service = selenium.webdriver.chrome.service.Service(common_config['service_location'])
    debugger_address = common_config['debugger_address']

    # 创建Chrome选项，重用现有的浏览器实例
    print(f"=====创建Chrome选项，重用现有的浏览器实例=====")
    options = selenium.webdriver.chrome.options.Options()
    options.page_load_strategy = 'normal'  # 设置页面加载策略为'normal' 默认值, 等待所有资源下载,
    options.add_experimental_option('debuggerAddress', debugger_address)
    options.binary_location = chrome_path
    options.add_argument("--remote-debugging-port=9222")

    # 使用服务和选项初始化WebDriver
    print(f"=====使用服务和选项初始化WebDriver=====")
    driver = webdriver.Chrome(service=service, options=options)
    print(f"-----WebDriver初始化完成-----")

    print(f"设置隐式等待时间为15秒")
    driver.implicitly_wait(15)  # 设置隐式等待时间为15秒

    return driver, common_config

    # all_sites_home = {
    #     'csdn': 'https://www.csdn.net/'
    # }


## start_page ###############################################################################
def start_page(site_url, driver):
    # 打开新标签页并切换到新标签页
    driver.switch_to.new_window('tab')
    # 浏览器实例现在可以被重用，进行你的自动化操作
    driver.get(site_url)
    time.sleep(1)

def force_click_by_js(driver,target_element):
    # 用 JavaScript 执行强制点击（忽略遮挡）
    driver.execute_script("arguments[0].click();", target_element)
    print("已通过JS强制点击目标按钮")
    target_element.click()
    time.sleep(0.5)

## csdn_publisher ###########################################################################
def csdn_publisher(common_config, driver, title, content, tags, categories):
    csdn_config = {
        "site_start": "https://www.csdn.net/",
        'site_editor': 'https://mp.csdn.net/mp_blog/creation/editor',  # 'https://editor.csdn.net/md/',

        'content': 'test-content',
        'title': title,
        'tags': ['学习', '英语学习'],  # 文章标签
        'categories': ['SaintOfAthena'],  # 文章分类：SaintOfAthena', 'ChinaDailyReading', 'GundamSeed', 'DragonBallOne'

        'title_xpath': '//*[@id="txtTitle"]',
        'content_xpath': '//*[@id="cke_editor"]',

        'tags_btn_xpath': '//button[@class="tag__btn-tag active"]',
        'tags_input_div_xpath': '//*[@id="moreDiv"]/div[1]/div/div/div[2]/div[2]/div/div',
        'tags_input_xpath': '/html/body/div[2]/div/section/section/div/div[1]/div/main/div[1]/form/div[5]/div[1]/div/div/div[2]/div[2]/div/div/div/input',

        'categories_btn_xpath': '//*[@id="tagList"]/button',

        'publish_btn_xpath': '//*[@id="moreDiv"]/div[12]/div/div/div[2]/button[3]',
        'save_btn_xpath': '//*[@id="moreDiv"]/div[12]/div/div/div[2]/button[1]',

        'visibility': '全部可见',
    }

    print(f"csdn_config={json.dumps(csdn_config, indent=4)}")

    def open_site():
        # 打开新标签页并切换到新标签页
        print(f"********打开编辑页面*************")
        print(f"打开新标签页并切换到Edit标签页")
        driver.switch_to.new_window('tab')
        # 浏览器实例现在可以被重用，进行你的自动化操作
        driver.get(csdn_config['site_editor'])
        time.sleep(2)  # 等待2秒

        # 等待页面加载
        print(f"等待文章标题html元素加载")
        wait_login(driver, By.XPATH, csdn_config['title_xpath'])
    open_site()

    # 文章标题
    def set_title():
        print(f"********文章标题*************")
        print(f"查找文章标题html元素")
        title = driver.find_element(By.XPATH, csdn_config['title_xpath'])
        print(f"清空并设置文章标题html元素")
        title.send_keys(csdn_config['title'])
        time.sleep(1)  # 等待3秒
    set_title()

    # 文章内容
    def set_content():
        print(f"********文章内容*************")

        # # 用的是CodeMirror,不能用元素赋值的方法，所以我们使用拷贝的方法
        cmd_ctrl = Keys.COMMAND if sys.platform == 'darwin' else Keys.CONTROL
        # # 将要粘贴的文本内容复制到剪贴板
        pyperclip.copy(csdn_config['content'])

        action_chains = webdriver.ActionChains(driver)

        content_area = driver.find_element(By.XPATH, csdn_config['content_xpath'])

        # 用 JavaScript 执行强制点击（忽略遮挡）
        force_click_by_js(driver,content_area)
        # driver.execute_script("arguments[0].click();", content_area)
        # print("已通过JS强制点击目标按钮")
        # content_area.click()
        # time.sleep(0.5)

        # 模拟实际的粘贴操作
        action_chains.key_down(cmd_ctrl).send_keys('v').key_up(cmd_ctrl).perform()
        time.sleep(3)  # 等待3秒

    set_content()

    # 文章标签
    def set_tag():
        print(f"********文章标签*************")
        for tag in csdn_config['tags']:
            print(f"tag={tag}")
            print(f"强行点击文章标签html元素")

            target_btn = WebDriverWait(driver, 10).until(
                EC.presence_of_element_located(
                    (By.XPATH, csdn_config['tags_btn_xpath'])
                )
            )
            # 用 JavaScript 执行强制点击（忽略遮挡）
            force_click_by_js(driver, target_btn)
            # driver.execute_script("arguments[0].click();", target_btn)
            # print("已通过JS强制点击目标按钮")
            # target_btn.click()
            # time.sleep(0.5)

            print(f"找到标签DIV，在输入前先激活")
            tag_div_input = driver.find_element(By.XPATH, csdn_config['tags_input_div_xpath'])
            tag_div_input.click()
            time.sleep(0.5)

            print(f"找到标签input")
            tag_input = driver.find_element(By.XPATH, csdn_config['tags_input_xpath'])

            print(f"输入标签值")
            tag_input.send_keys(tag)
            time.sleep(1)
            tag_input.send_keys(Keys.ENTER)
            time.sleep(1)
        # 随便点击一个地方收回标签面板
        script = "var el = document.elementFromPoint(arguments[0], arguments[1]); if (el) { el.click(); }"
        driver.execute_script(script, 1, 1)
    set_tag()

    def set_categories():
        print(f"********文章分类*************")
        print(f"设置分类专栏")
        categories = csdn_config['categories']
        if categories:
            # 先点击新建分类专栏
            add_category = driver.find_element(By.XPATH, csdn_config['categories_btn_xpath'])
            add_category.click()
            time.sleep(1)
            for category in categories:
                category_input = driver.find_element(By.XPATH, f'//input[@type="checkbox" and @value="{category}"]/..')
                category_input.click()
                time.sleep(1)
        # 随便点击一个地方收回分类面板
        script = "var el = document.elementFromPoint(arguments[0], arguments[1]); if (el) { el.click(); }"
        driver.execute_script(script, 1, 1)
    set_categories()

    def save_article():
        print(f"********保存文稿*************")
        save_button = driver.find_element(By.XPATH, csdn_config['save_btn_xpath'])
        save_button.click()
        time.sleep(1)
    save_article()

    def publish_article():
        print(f"********发布文章[{common_config['auto_publish']}]*************")
        # 发布
        if common_config['auto_publish']:
            publish_button = driver.find_element(By.XPATH, csdn_config['publish_btn_xpath'])
            publish_button.click()
    publish_article()
#################################################################################


def run_main():
    """
    发布到所有平台的封装函数
    """
    driver, common_config = init_driver()

    # driver.get("chrome://version/")
    # start_page(csdn_conf['site_start'], driver)

    # for i in range(8):
    #     index = 70+i
    #     for j in range(2):
    #         subindex = 1+j
    #         title = f'英语学习-Saints0{index}-{subindex}'
    #         print(title)
    #         csdn_publisher(common_config,driver,title)

    csdn_publisher(common_config, driver,
                   content='test-content',
                   title="title-test",
                   tags=['学习', '英语学习'],     # 文章标签
                   categories=['SaintOfAthena'] # 文章分类：SaintOfAthena', 'ChinaDailyReading', 'GundamSeed', 'DragonBallOne'
                   )

    # 在需要的时候关闭浏览器，不要关闭浏览器进程
    driver.quit()


if __name__ == '__main__':
    print(f"Hello")
    run_main()
